# @Time : 2020/10/19 16:24
# @Author : Fioman 
# @Phone : 13149920693
import time
from xml.dom.minidom import parse,Document



# 解析接收到的消息
def parse_recv_msg(msgRecv):
    if msgRecv == "MESSAGE_ERROR":
        return None, None
    write_recv_message(msgRecv)
    dom = parse(r"./message_recv.xml")
    rootNode = dom.documentElement
    msgNameNode = rootNode.getElementsByTagName("messagename")[0]
    bodyDict = {}
    bodyNode = rootNode.getElementsByTagName("body")[0]
    for node in bodyNode.childNodes:
        if node.nodeName != "#text":
            bodyDict[node.nodeName] = node.childNodes[0].data
    retNode = rootNode.getElementsByTagName("returncode")[0]
    msgName = msgNameNode.childNodes[0].data
    retCode = retNode.childNodes[0].data
    return msgName,bodyDict,retCode

def pack_send_msg(msgName,bodyDict,retCode):
    print("in pack_send_msg(), msgName = {},bodyDict = {},retCode = {}".format(msgName,bodyDict,retCode))
    doc = Document() # 在内存中创建一个空的文档
    root = doc.createElement("message") # 创建根节点
    doc.appendChild(root)  # 将根节点添加到文件对象中


    # 然后将head的消息和body的消息以及ret的消息填入
    headNode = doc.createElement("head") # 创建head节点
    msgNameNode = doc.createElement("messagename")  # 创建消息名称节点
    msgNameNode.appendChild(doc.createTextNode(msgName)) # 消息名称的文字节点
    transactionId = get_transaction_id()
    idNode = doc.createElement("transactionid")
    idNode.appendChild(doc.createTextNode(transactionId))
    headNode.appendChild(msgNameNode)
    headNode.appendChild(idNode)
    # 头部节点创建完成

    bodyNode = doc.createElement("body")
    if msgName == "Recipe Body Reply":
        recipeNameNode = doc.createElement("recipe_name")
        recipeDataListNode = doc.createElement("recipe_body_list")
        recipeName = bodyDict[0]
        for item in bodyDict[1]:
            recipeListNode = doc.createElement("recipe_body")
            dataItemNode = doc.createElement("data_item")
            dataValueNode = doc.createElement("data_value")
            dataItemNode.appendChild(doc.createTextNode(item[0]))
            dataValueNode.appendChild(doc.createTextNode(item[1]))
            recipeListNode.appendChild(dataItemNode)
            recipeListNode.appendChild(dataValueNode)
            recipeDataListNode.appendChild(recipeListNode)
        recipeNameNode.appendChild(doc.createTextNode(recipeName))
        bodyNode.appendChild(recipeNameNode)
        bodyNode.appendChild(recipeDataListNode)
    elif msgName == "Trace Data Reply":
        traceDataListNode = doc.createElement("trace_data_list")
        for item in bodyDict:
            traceListNode = doc.createElement("trace_data")
            dataNoNode = doc.createElement("data_no")
            dataItemNode = doc.createElement("data_item")
            dataValueNode = doc.createElement("data_value")
            dataNoNode.appendChild(doc.createTextNode(item[0]))
            dataItemNode.appendChild(doc.createTextNode(item[1]))
            dataValueNode.appendChild(doc.createTextNode(item[2]))
            traceListNode.appendChild(dataNoNode)
            traceListNode.appendChild(dataItemNode)
            traceListNode.appendChild(dataValueNode)
            traceDataListNode.appendChild(traceListNode)
        bodyNode.appendChild(traceDataListNode)
    elif msgName == "Process Data Report":
        rePortTypeNode = doc.createElement("report_type")
        judgeTypeNode = doc.createElement("judge")
        proceNameNode = doc.createElement("proc_name")
        rePortTypeNode.appendChild(doc.createTextNode(bodyDict[0]))
        judgeTypeNode.appendChild(doc.createTextNode(bodyDict[1]))
        proceNameNode.appendChild(doc.createTextNode(bodyDict[2]))

        procDataListNode = doc.createElement("proc_data_list")
        for item in bodyDict[3]:
            procDataNode = doc.createElement("proc_data")
            dataItemNode = doc.createElement("data_item")
            dataValueNode = doc.createElement("data_value")
            dataItemNode.appendChild(doc.createTextNode(item[0]))
            dataValueNode.appendChild(doc.createTextNode(item[1]))
            procDataNode.appendChild(dataItemNode)
            procDataNode.appendChild(dataValueNode)
            procDataListNode.appendChild(procDataNode)
        bodyNode.appendChild(rePortTypeNode)
        bodyNode.appendChild(judgeTypeNode)
        bodyNode.appendChild(proceNameNode)
        bodyNode.appendChild(procDataListNode)

    else:
        for element, value in bodyDict.items():
            node = doc.createElement(element)
            node.appendChild(doc.createTextNode(value))
            bodyNode.appendChild(node)

    retNode = doc.createElement("return")
    for element,value in retCode.items():
        node = doc.createElement(element)
        if value != "":
            node.appendChild(doc.createTextNode(value))
        retNode.appendChild(node)

    # 然后将head_node,body_node,ret_node加到根节点root节点上面去
    root.appendChild(headNode)
    root.appendChild(bodyNode)
    root.appendChild(retNode)

    if msgName == "Are You There Request":
        fp1 = open(r'./ask_msg.xml', 'w')
        doc.writexml(fp1, indent='', addindent='\t', newl='\n', encoding='utf-8')
        fp1.close()
    else:
        fp2 = open(r'./send_msg.xml', 'w')
        doc.writexml(fp2, indent='', addindent='\t', newl='\n', encoding='utf-8')
        fp2.close()


# 获取通信标识符
def get_transaction_id():
    now_second = time.time()
    last_three = str(now_second).split('.')[1][:3]
    now = time.strftime("%Y%m%d%H%M%S", time.localtime(now_second))
    transaction_id = now + last_three
    return transaction_id

def write_recv_message(messageRecv):
    with open("./message_recv.xml", "wb") as f:
        f.write(messageRecv[1:-1])  # 去除前两个字节.一个是char(2),一个是char(3)
